package com.lensyn.generator.plugins;

import com.lensyn.generator.domain.MsgKey;
import com.lensyn.generator.handler.EntityMetaHandler;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.api.dom.java.JavaVisibility;
import org.mybatis.generator.api.dom.java.TopLevelClass;

import java.util.List;

/**
 * @author xiaob@lensysn.com
 * @date 2017/2/16
 */
public class GenerateEntityMeta {
    IntrospectedTable introspectedTable;
    EntityMetaHandler entityMetaHandler;

    public GenerateEntityMeta(IntrospectedTable introspectedTable, EntityMetaHandler entityMetaHandler) {
        this.introspectedTable = introspectedTable;
        this.entityMetaHandler = entityMetaHandler;
    }

    public TopLevelClass generate() {

        TopLevelClass entityClass = new TopLevelClass(entityMetaHandler.entityMetaName(
                introspectedTable.getFullyQualifiedTable().getIntrospectedTableName()
        ));

        entityClass.setVisibility(JavaVisibility.PUBLIC);
        entityClass.setFinal(true);

        List<IntrospectedColumn> introspectedColumns = introspectedTable.getAllColumns();

        for (IntrospectedColumn introspectedColumn : introspectedColumns) {
            generateField(introspectedColumn, entityClass, false);
        }

        return entityClass;
    }

    private void generateField(IntrospectedColumn introspectedColumn, TopLevelClass entityClass, boolean b) {

        FullyQualifiedJavaType fqjt = new FullyQualifiedJavaType("String");

        String property = introspectedColumn.getJavaProperty();

        Field field = new Field();
        field.setVisibility(JavaVisibility.PUBLIC);
        field.setFinal(true);
        field.setStatic(true);
        field.setType(fqjt);
        field.setName(property);
        field.setInitializationString("\""+property+"\"");

        entityClass.addField(field);
        entityClass.addImportedType(field.getType());
    }
}
